"""
现代化模板管理页面

基于 template_library_page.py 创建的现代化模板管理界面
"""

import customtkinter as ctk
from typing import List, Dict, Any, Optional
from pathlib import Path
import sys

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))

from ..themes import ModernTheme
from ..components import ModernButton, ModernCard, StatusBadge
from ..layouts import GridLayout

# 导入数据库相关
try:
    from src.repositories.jianying_template_repository import JianyingTemplateRepository
    from src.core.di import injector
    TEMPLATE_REPO_AVAILABLE = True
except ImportError as e:
    print(f"导入数据库相关模块失败: {e}")
    TEMPLATE_REPO_AVAILABLE = False


class TemplateManagementPage(ctk.CTkFrame):
    """现代化模板管理页面"""

    def __init__(self, parent):
        super().__init__(parent, fg_color="transparent")
        
        # 初始化模板仓库
        self.template_repo = None
        self.repo_error_message = ""

        if TEMPLATE_REPO_AVAILABLE:
            try:
                self.template_repo = injector.get(JianyingTemplateRepository)
                print("✅ 成功获取模板仓库")
            except Exception as e:
                self.repo_error_message = f"无法获取模板仓库: {e}"
                print(f"❌ {self.repo_error_message}")
        else:
            self.repo_error_message = "数据库相关模块导入失败"
            print(f"❌ {self.repo_error_message}")
        
        # 当前选中的模板
        self.selected_templates = []
        self.current_filter = {"segments": "全部", "canvas": "全部", "status": "全部", "search": ""}
        
        self.create_page()
        self.load_templates()

    def show_message(self, title: str, message: str, msg_type: str = "info"):
        """显示消息对话框"""
        try:
            import tkinter as tk
            from tkinter import messagebox

            # 创建临时根窗口
            temp_root = tk.Tk()
            temp_root.withdraw()
            temp_root.lift()
            temp_root.attributes('-topmost', True)

            # 根据消息类型显示不同的对话框
            if msg_type == "error":
                messagebox.showerror(title, message, parent=temp_root)
            elif msg_type == "warning":
                messagebox.showwarning(title, message, parent=temp_root)
            elif msg_type == "success":
                messagebox.showinfo(title, message, parent=temp_root)
            else:  # info
                messagebox.showinfo(title, message, parent=temp_root)

            temp_root.destroy()

        except Exception as e:
            print(f"显示消息失败: {e}")
            print(f"{title}: {message}")

    def create_page(self):
        """创建页面内容"""
        # 创建主容器
        self.main_container = ctk.CTkFrame(self, fg_color="transparent")
        self.main_container.pack(fill="both", expand=True, padx=20, pady=16)
        
        # 创建滚动容器
        self.scroll_frame = ctk.CTkScrollableFrame(
            self.main_container,
            fg_color="transparent",
            scrollbar_fg_color=ModernTheme.get_color('bg_tertiary'),
            scrollbar_button_color=ModernTheme.get_color('border_medium')
        )
        self.scroll_frame.pack(fill="both", expand=True)
        
        # 页面标题
        self.create_header()
        
        # 工具栏
        self.create_toolbar()
        
        # 筛选器
        self.create_filters()
        
        # 状态栏
        self.create_status_bar()
        
        # 模板列表
        self.create_template_list()

    def create_header(self):
        """创建页面标题"""
        header_frame = ctk.CTkFrame(self.scroll_frame, fg_color="transparent")
        header_frame.pack(fill="x", pady=(0, ModernTheme.SIZES['spacing_xl']))
        
        # 主标题
        title = ctk.CTkLabel(
            header_frame,
            text="🎨 模板管理",
            font=ModernTheme.get_font('title'),
            text_color=ModernTheme.COLORS['primary']
        )
        title.pack(anchor="w")
        
        # 副标题
        subtitle = ctk.CTkLabel(
            header_frame,
            text="管理和组织您的剪映模板库",
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_secondary')
        )
        subtitle.pack(anchor="w", pady=(ModernTheme.SIZES['spacing_xs'], 0))

    def create_toolbar(self):
        """创建工具栏"""
        toolbar_card = ModernCard(self.scroll_frame)
        toolbar_card.pack(fill="x", pady=(0, ModernTheme.SIZES['spacing_lg']))
        
        # 主要操作按钮
        main_actions_frame = ctk.CTkFrame(toolbar_card.content_frame, fg_color="transparent")
        main_actions_frame.pack(fill="x", pady=(0, ModernTheme.SIZES['spacing_md']))
        
        # 导入操作
        import_frame = ctk.CTkFrame(main_actions_frame, fg_color="transparent")
        import_frame.pack(side="left", fill="y")
        
        import_label = ctk.CTkLabel(
            import_frame,
            text="📥 导入模板",
            font=ModernTheme.get_font('body_bold'),
            text_color=ModernTheme.get_color('text_primary')
        )
        import_label.pack(anchor="w")
        
        import_buttons_frame = ctk.CTkFrame(import_frame, fg_color="transparent")
        import_buttons_frame.pack(fill="x", pady=(ModernTheme.SIZES['spacing_xs'], 0))
        
        ModernButton(
            import_buttons_frame,
            text="单个导入",
            command=self.import_single_template,
            variant="primary"
        ).pack(side="left", padx=(0, ModernTheme.SIZES['spacing_sm']))

        ModernButton(
            import_buttons_frame,
            text="批量导入",
            command=self.batch_import_templates,
            variant="secondary"
        ).pack(side="left")
        
        # 分隔线
        separator = ctk.CTkFrame(main_actions_frame, width=2, height=60, fg_color=ModernTheme.get_color('border_light'))
        separator.pack(side="left", padx=ModernTheme.SIZES['spacing_lg'], fill="y")
        
        # 管理操作
        manage_frame = ctk.CTkFrame(main_actions_frame, fg_color="transparent")
        manage_frame.pack(side="left", fill="y")
        
        manage_label = ctk.CTkLabel(
            manage_frame,
            text="🛠️ 管理操作",
            font=ModernTheme.get_font('body_bold'),
            text_color=ModernTheme.get_color('text_primary')
        )
        manage_label.pack(anchor="w")
        
        manage_buttons_frame = ctk.CTkFrame(manage_frame, fg_color="transparent")
        manage_buttons_frame.pack(fill="x", pady=(ModernTheme.SIZES['spacing_xs'], 0))
        
        ModernButton(
            manage_buttons_frame,
            text="删除选中",
            command=self.delete_selected_templates,
            variant="error"
        ).pack(side="left", padx=(0, ModernTheme.SIZES['spacing_sm']))

        ModernButton(
            manage_buttons_frame,
            text="刷新列表",
            command=self.refresh_templates,
            variant="secondary"
        ).pack(side="left")

    def create_filters(self):
        """创建筛选器"""
        filter_card = ModernCard(self.scroll_frame)
        filter_card.pack(fill="x", pady=(0, ModernTheme.SIZES['spacing_lg']))
        
        filters_frame = ctk.CTkFrame(filter_card.content_frame, fg_color="transparent")
        filters_frame.pack(fill="x")
        
        # 片段数筛选
        segments_frame = ctk.CTkFrame(filters_frame, fg_color="transparent")
        segments_frame.pack(side="left", padx=(0, ModernTheme.SIZES['spacing_lg']))

        ctk.CTkLabel(
            segments_frame,
            text="片段数:",
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_secondary')
        ).pack(anchor="w")

        self.segments_filter = ctk.CTkComboBox(
            segments_frame,
            values=["全部", "1-3个", "4-6个", "7-10个", "10个以上"],
            command=self.on_filter_changed,
            width=120
        )
        self.segments_filter.pack(pady=(ModernTheme.SIZES['spacing_xs'], 0))
        self.segments_filter.set("全部")
        
        # 画布比例筛选
        canvas_frame = ctk.CTkFrame(filters_frame, fg_color="transparent")
        canvas_frame.pack(side="left", padx=(0, ModernTheme.SIZES['spacing_lg']))
        
        ctk.CTkLabel(
            canvas_frame,
            text="画布比例:",
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_secondary')
        ).pack(anchor="w")
        
        self.canvas_filter = ctk.CTkComboBox(
            canvas_frame,
            values=["全部", "16:9", "9:16", "1:1", "4:3"],
            command=self.on_filter_changed,
            width=120
        )
        self.canvas_filter.pack(pady=(ModernTheme.SIZES['spacing_xs'], 0))
        self.canvas_filter.set("全部")
        
        # 状态筛选
        status_frame = ctk.CTkFrame(filters_frame, fg_color="transparent")
        status_frame.pack(side="left", padx=(0, ModernTheme.SIZES['spacing_lg']))

        ctk.CTkLabel(
            status_frame,
            text="状态:",
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_secondary')
        ).pack(anchor="w")

        self.status_filter = ctk.CTkComboBox(
            status_frame,
            values=["全部", "启用", "禁用"],
            command=self.on_filter_changed,
            width=120
        )
        self.status_filter.pack(pady=(ModernTheme.SIZES['spacing_xs'], 0))
        self.status_filter.set("全部")

        # 搜索框
        search_frame = ctk.CTkFrame(filters_frame, fg_color="transparent")
        search_frame.pack(side="left")

        ctk.CTkLabel(
            search_frame,
            text="搜索:",
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_secondary')
        ).pack(anchor="w")

        self.search_entry = ctk.CTkEntry(
            search_frame,
            placeholder_text="输入模板名称...",
            width=150
        )
        self.search_entry.pack(pady=(ModernTheme.SIZES['spacing_xs'], 0))
        self.search_entry.bind("<KeyRelease>", self.on_search_changed)

    def create_status_bar(self):
        """创建状态栏"""
        status_frame = ctk.CTkFrame(self.scroll_frame, fg_color="transparent")
        status_frame.pack(fill="x", pady=(0, ModernTheme.SIZES['spacing_md']))
        
        self.status_label = ctk.CTkLabel(
            status_frame,
            text="正在加载模板...",
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_secondary')
        )
        self.status_label.pack(side="left")
        
        self.selection_label = ctk.CTkLabel(
            status_frame,
            text="",
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.COLORS['success']
        )
        self.selection_label.pack(side="right")

    def create_template_list(self):
        """创建模板列表"""
        list_card = ModernCard(self.scroll_frame)
        list_card.pack(fill="both", expand=True)
        
        # 创建表格容器
        self.template_list_frame = ctk.CTkFrame(list_card.content_frame, fg_color="transparent")
        self.template_list_frame.pack(fill="both", expand=True)
        
        # 表格标题行
        self.create_table_header()
        
        # 模板项容器
        self.template_items_frame = ctk.CTkFrame(
            self.template_list_frame,
            fg_color=ModernTheme.get_color('bg_secondary')
        )
        self.template_items_frame.pack(fill="both", expand=True, pady=(ModernTheme.SIZES['spacing_xs'], 0))

    def create_table_header(self):
        """创建表格标题行"""
        header_frame = ctk.CTkFrame(
            self.template_list_frame,
            fg_color=ModernTheme.get_color('bg_tertiary'),
            height=40
        )
        header_frame.pack(fill="x", pady=(0, 2))
        header_frame.pack_propagate(False)
        
        headers = [
            ("选择", 60),
            ("模板名称", 200),
            ("类型", 100),
            ("时长", 80),
            ("画布比例", 100),
            ("片段数", 80),
            ("状态", 100),
            ("操作", 120)
        ]
        
        for header, width in headers:
            label = ctk.CTkLabel(
                header_frame,
                text=header,
                font=ModernTheme.get_font('body_bold'),
                text_color=ModernTheme.get_color('text_primary'),
                width=width
            )
            label.pack(side="left", padx=ModernTheme.SIZES['spacing_xs'], pady=8)

    def load_templates(self):
        """加载模板数据"""
        if not self.template_repo:
            # 如果没有数据库连接，显示示例数据
            error_msg = f"数据库连接不可用: {self.repo_error_message}"
            self.status_label.configure(text=error_msg)
            print(f"⚠️ {error_msg}")
            return

        try:
            # 从数据库获取模板列表
            templates = self.template_repo.get_all()

            if not templates:
                # 如果数据库中没有模板，显示空状态
                self.display_empty_state()
                self.status_label.configure(text="数据库中暂无模板数据")
                return

            # 转换数据库数据格式为显示格式
            display_templates = self.convert_db_templates_to_display_format(templates)
            self.display_templates(display_templates)

            # 更新状态
            self.status_label.configure(text=f"从数据库加载 {len(templates)} 个模板")

        except Exception as e:
            # 如果数据库查询失败，显示示例数据
            self.status_label.configure(text=f"数据库加载失败，显示示例数据: {str(e)}")
            print(f"加载模板失败: {e}")

    def convert_db_templates_to_display_format(self, db_templates):
        """将数据库模板数据转换为显示格式"""
        display_templates = []

        for template in db_templates:
            # 如果是模型对象，转换为字典
            if hasattr(template, 'to_dict'):
                template_dict = template.to_dict()
            else:
                template_dict = template

            # 根据数据库字段映射到显示字段
            display_template = {
                "id": template_dict.get("id"),  # 数据库主键ID
                "template_id": template_dict.get("template_id"),  # 模板业务ID
                "name": template_dict.get("template_name", "未知模板"),
                "type": self.get_template_type(template_dict),
                "duration": template_dict.get("duration_seconds", 0),
                "canvas_ratio": template_dict.get("canvas_ratio", "未知"),
                "video_segment_count": template_dict.get("video_segments_count", 0),
                "status": self.get_template_status(template_dict),
                "file_path": template_dict.get("template_path", ""),
                "created_at": template_dict.get("created_at"),
                "updated_at": template_dict.get("updated_at")
            }
            display_templates.append(display_template)

        return display_templates

    def get_template_type(self, template):
        """获取模板类型"""
        # 目前只有剪映模板
        return "剪映模板"

    def get_template_status(self, template):
        """获取模板状态"""
        # 根据 is_enabled 字段返回启用/禁用状态
        is_enabled = template.get("is_enabled", True)
        return "启用" if is_enabled else "禁用"

    def display_empty_state(self):
        """显示空状态"""
        # 清空现有项目
        for widget in self.template_items_frame.winfo_children():
            widget.destroy()

        # 显示空状态提示
        empty_frame = ctk.CTkFrame(self.template_items_frame, fg_color="transparent")
        empty_frame.pack(fill="both", expand=True, pady=50)

        empty_icon = ctk.CTkLabel(
            empty_frame,
            text="📦",
            font=ctk.CTkFont(size=48),
            text_color=ModernTheme.get_color('text_secondary')
        )
        empty_icon.pack(pady=(0, 10))

        empty_title = ctk.CTkLabel(
            empty_frame,
            text="暂无模板数据",
            font=ModernTheme.get_font('heading'),
            text_color=ModernTheme.get_color('text_secondary')
        )
        empty_title.pack(pady=(0, 5))

        empty_desc = ctk.CTkLabel(
            empty_frame,
            text="点击上方的导入按钮开始添加模板",
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_tertiary')
        )
        empty_desc.pack()

    
    def display_templates(self, templates: List[Dict[str, Any]]):
        """显示模板列表"""
        # 清空现有项目
        for widget in self.template_items_frame.winfo_children():
            widget.destroy()

        # 应用筛选
        filtered_templates = self.filter_templates(templates)

        # 创建模板项
        for template in filtered_templates:
            self.create_template_item(template)

        # 更新选择状态
        self.update_selection_status()

    def filter_templates(self, templates: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """根据筛选条件过滤模板"""
        filtered = templates

        # 片段数筛选
        if self.current_filter["segments"] != "全部":
            segments_filter = self.current_filter["segments"]
            if segments_filter == "1-3个":
                filtered = [t for t in filtered if 1 <= t.get("video_segment_count", 0) <= 3]
            elif segments_filter == "4-6个":
                filtered = [t for t in filtered if 4 <= t.get("video_segment_count", 0) <= 6]
            elif segments_filter == "7-10个":
                filtered = [t for t in filtered if 7 <= t.get("video_segment_count", 0) <= 10]
            elif segments_filter == "10个以上":
                filtered = [t for t in filtered if t.get("video_segment_count", 0) > 10]

        # 画布比例筛选
        if self.current_filter["canvas"] != "全部":
            filtered = [t for t in filtered if t.get("canvas_ratio") == self.current_filter["canvas"]]

        # 状态筛选
        if self.current_filter["status"] != "全部":
            filtered = [t for t in filtered if t.get("status") == self.current_filter["status"]]

        # 搜索筛选
        search_text = self.current_filter["search"].lower()
        if search_text:
            filtered = [t for t in filtered if search_text in t.get("name", "").lower()]

        return filtered

    def create_template_item(self, template: Dict[str, Any]):
        """创建单个模板项"""
        item_frame = ctk.CTkFrame(
            self.template_items_frame,
            fg_color=ModernTheme.get_color('bg_primary'),
            height=50
        )
        item_frame.pack(fill="x", pady=1)
        item_frame.pack_propagate(False)

        # 选择框
        checkbox = ctk.CTkCheckBox(
            item_frame,
            text="",
            width=60,
            command=lambda: self.on_template_selected(template, checkbox)
        )
        checkbox.pack(side="left", padx=ModernTheme.SIZES['spacing_xs'], pady=8)

        # 模板名称
        name_label = ctk.CTkLabel(
            item_frame,
            text=template.get("name", "未知模板"),
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_primary'),
            width=200,
            anchor="w"
        )
        name_label.pack(side="left", padx=ModernTheme.SIZES['spacing_xs'], pady=8)

        # 类型
        type_label = ctk.CTkLabel(
            item_frame,
            text=template.get("type", "未知"),
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_secondary'),
            width=100
        )
        type_label.pack(side="left", padx=ModernTheme.SIZES['spacing_xs'], pady=8)

        # 时长
        duration = template.get("duration", 0)
        duration_text = f"{duration:.1f}s" if duration else "未知"
        duration_label = ctk.CTkLabel(
            item_frame,
            text=duration_text,
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_secondary'),
            width=80
        )
        duration_label.pack(side="left", padx=ModernTheme.SIZES['spacing_xs'], pady=8)

        # 画布比例
        canvas_label = ctk.CTkLabel(
            item_frame,
            text=template.get("canvas_ratio", "未知"),
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_secondary'),
            width=100
        )
        canvas_label.pack(side="left", padx=ModernTheme.SIZES['spacing_xs'], pady=8)

        # 片段数
        segments_label = ctk.CTkLabel(
            item_frame,
            text=str(template.get("video_segment_count", 0)),
            font=ModernTheme.get_font('body'),
            text_color=ModernTheme.get_color('text_secondary'),
            width=80
        )
        segments_label.pack(side="left", padx=ModernTheme.SIZES['spacing_xs'], pady=8)

        # 状态
        status = template.get("status", "未知")
        status_badge = StatusBadge(
            item_frame,
            text=status,
            status=self.get_status_type(status),
            width=100
        )
        status_badge.pack(side="left", padx=ModernTheme.SIZES['spacing_xs'], pady=8)

        # 操作按钮
        actions_frame = ctk.CTkFrame(item_frame, fg_color="transparent", width=120)
        actions_frame.pack(side="left", padx=ModernTheme.SIZES['spacing_xs'], pady=8)
        actions_frame.pack_propagate(False)

        # 查看按钮
        view_btn = ctk.CTkButton(
            actions_frame,
            text="查看",
            width=50,
            height=25,
            font=ModernTheme.get_font('body_sm'),
            command=lambda: self.view_template(template)
        )
        view_btn.pack(side="left", padx=(0, 4))

        # 删除按钮
        delete_btn = ctk.CTkButton(
            actions_frame,
            text="删除",
            width=50,
            height=25,
            font=ModernTheme.get_font('body_sm'),
            fg_color=ModernTheme.COLORS['error'],
            hover_color="#E6342A",
            command=lambda: self.delete_template(template)
        )
        delete_btn.pack(side="left")

    def get_status_type(self, status: str) -> str:
        """获取状态类型"""
        status_map = {
            "正常": "success",
            "缺失文件": "warning",
            "损坏": "error"
        }
        return status_map.get(status, "default")

    # 事件处理方法
    def on_filter_changed(self, value=None):
        """筛选条件改变"""
        self.current_filter["segments"] = self.segments_filter.get()
        self.current_filter["canvas"] = self.canvas_filter.get()
        self.current_filter["status"] = self.status_filter.get()
        self.load_templates()

    def on_search_changed(self, event=None):
        """搜索条件改变"""
        self.current_filter["search"] = self.search_entry.get()
        self.load_templates()

    def on_template_selected(self, template: Dict[str, Any], checkbox):
        """模板选择状态改变"""
        if checkbox.get():
            if template not in self.selected_templates:
                self.selected_templates.append(template)
        else:
            if template in self.selected_templates:
                self.selected_templates.remove(template)

        self.update_selection_status()

    def update_selection_status(self):
        """更新选择状态显示"""
        count = len(self.selected_templates)
        if count > 0:
            self.selection_label.configure(text=f"已选择 {count} 个模板")
        else:
            self.selection_label.configure(text="")

    # 操作方法
    def import_single_template(self):
        """单个导入模板"""
        try:
            import tkinter as tk
            from tkinter import filedialog, messagebox
            from pathlib import Path

            # 创建一个临时的根窗口（隐藏）
            temp_root = tk.Tk()
            temp_root.withdraw()  # 隐藏窗口
            temp_root.lift()      # 提升到前台
            temp_root.attributes('-topmost', True)  # 置顶

            # 选择模板目录
            template_dir = filedialog.askdirectory(
                parent=temp_root,
                title="选择剪映模板目录",
                initialdir=str(Path("dist/剪映模板")) if Path("dist/剪映模板").exists() else None
            )

            temp_root.destroy()  # 销毁临时窗口

            if template_dir:
                try:
                    template_path = Path(template_dir)

                    # 检查是否是有效的模板目录
                    required_files = ["draft_content.json", "draft_meta_info.json"]
                    missing_files = []

                    for file_name in required_files:
                        if not (template_path / file_name).exists():
                            missing_files.append(file_name)

                    if missing_files:
                        self.show_message(
                            "无效的模板目录",
                            f"选择的目录不是有效的剪映模板目录。\n\n缺少必要文件:\n{chr(10).join(missing_files)}\n\n请选择包含 draft_content.json 和 draft_meta_info.json 的模板目录。",
                            "error"
                        )
                        return

                    # 显示确认对话框
                    temp_root2 = tk.Tk()
                    temp_root2.withdraw()
                    temp_root2.lift()
                    temp_root2.attributes('-topmost', True)

                    confirm_msg = f"确定要导入模板吗？\n\n模板路径: {template_path}\n模板名称: {template_path.name}"
                    result = messagebox.askyesno("确认导入", confirm_msg, parent=temp_root2)
                    temp_root2.destroy()

                    if not result:
                        return

                    # 尝试导入模板
                    import_result = self.process_single_template_import(template_path)

                    if import_result["success"]:
                        self.show_message("导入成功", import_result["message"], "success")
                        self.refresh_templates()
                    else:
                        self.show_message("导入失败", import_result["message"], "error")

                except Exception as e:
                    self.show_message("导入失败", f"导入模板失败: {str(e)}", "error")

        except Exception as e:
            self.show_message("错误", f"无法打开目录选择对话框: {str(e)}", "error")

    def process_single_template_import(self, template_path):
        """处理单个模板导入"""
        try:
            # 如果有模板仓库，使用真实的导入逻辑
            if self.template_repo:
                try:
                    from src.services.jianying_template_scanner import JianyingTemplateScanner
                    from src.core.di import injector

                    scanner = injector.get(JianyingTemplateScanner)
                    result = scanner._process_single_template(template_path, force_update=True)

                    return {
                        "success": True,
                        "template_id": result["template_id"],
                        "action": result["action"],
                        "video_segments_count": result.get("video_segments_count", 0),
                        "message": f"✅ 模板导入成功！\n\n模板名称: {template_path.name}\n操作类型: {'更新' if result['action'] == 'updated' else '创建'}\n视频片段数: {result.get('video_segments_count', 0)}个\n模板ID: {result['template_id']}"
                    }
                except Exception as e:
                    return {
                        "success": False,
                        "error": str(e),
                        "message": f"❌ 模板导入失败！\n\n模板名称: {template_path.name}\n错误信息: {str(e)}"
                    }
            else:
                # 如果没有数据库连接，模拟导入成功
                return {
                    "success": True,
                    "message": f"✅ 模板导入成功！（模拟）\n\n模板名称: {template_path.name}\n模板路径: {template_path}\n\n注意: 当前没有数据库连接，这是模拟导入。"
                }

        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "message": f"❌ 导入过程中发生错误: {str(e)}"
            }

    def batch_import_templates(self):
        """批量导入模板"""
        try:
            import tkinter as tk
            from tkinter import filedialog, messagebox
            from pathlib import Path

            # 创建一个临时的根窗口（隐藏）
            temp_root = tk.Tk()
            temp_root.withdraw()  # 隐藏窗口
            temp_root.lift()      # 提升到前台
            temp_root.attributes('-topmost', True)  # 置顶

            # 选择包含多个模板的根目录
            template_root_dir = filedialog.askdirectory(
                parent=temp_root,
                title="选择包含多个模板的根目录",
                initialdir=str(Path("dist/剪映模板")) if Path("dist/剪映模板").exists() else None
            )

            temp_root.destroy()  # 销毁临时窗口

            if template_root_dir:
                try:
                    template_root_path = Path(template_root_dir)

                    # 查找所有有效的模板目录
                    template_dirs = []
                    for item in template_root_path.iterdir():
                        if item.is_dir():
                            # 检查是否包含必要的模板文件
                            if (item / "draft_content.json").exists() and (item / "draft_meta_info.json").exists():
                                template_dirs.append(item)

                    if not template_dirs:
                        self.show_message("未找到模板", f"在目录 {template_root_path} 中未找到有效的模板目录。\n\n有效的模板目录应包含:\n- draft_content.json\n- draft_meta_info.json", "warning")
                        return

                    # 确认批量导入
                    temp_root2 = tk.Tk()
                    temp_root2.withdraw()
                    temp_root2.lift()
                    temp_root2.attributes('-topmost', True)

                    confirm_msg = f"找到 {len(template_dirs)} 个模板目录，确定要批量导入吗？\n\n模板列表:\n"
                    for i, template_dir in enumerate(template_dirs[:5], 1):
                        confirm_msg += f"{i}. {template_dir.name}\n"
                    if len(template_dirs) > 5:
                        confirm_msg += f"... 还有 {len(template_dirs) - 5} 个模板"

                    result = messagebox.askyesno("确认批量导入", confirm_msg, parent=temp_root2)
                    temp_root2.destroy()

                    if not result:
                        return

                    # 执行批量导入
                    success_count = 0
                    error_count = 0
                    results = []

                    for template_dir in template_dirs:
                        try:
                            import_result = self.process_single_template_import(template_dir)
                            if import_result["success"]:
                                success_count += 1
                                results.append((template_dir.name, import_result))
                            else:
                                error_count += 1
                                results.append((template_dir.name, import_result))
                        except Exception as e:
                            error_count += 1
                            results.append((template_dir.name, {"success": False, "error": str(e)}))

                    # 显示批量导入结果
                    self.show_batch_import_result(success_count, error_count, results)

                    if success_count > 0:
                        self.refresh_templates()

                except Exception as e:
                    self.show_message("批量导入失败", f"批量导入过程中发生错误: {str(e)}", "error")

        except Exception as e:
            self.show_message("错误", f"无法打开目录选择对话框: {str(e)}", "error")

    def show_batch_import_result(self, success_count: int, error_count: int, results: list):
        """显示批量导入结果"""
        total_count = success_count + error_count

        result_msg = f"📊 批量导入完成！\n\n"
        result_msg += f"总计: {total_count} 个模板\n"
        result_msg += f"成功: {success_count} 个\n"
        result_msg += f"失败: {error_count} 个\n"
        result_msg += f"成功率: {success_count / total_count * 100:.1f}%\n"

        if error_count > 0:
            result_msg += f"\n失败的模板:\n"
            error_results = [r for r in results if not r[1]["success"]]
            for template_name, result in error_results[:5]:  # 只显示前5个错误
                error_msg = result.get("error", "未知错误")
                result_msg += f"• {template_name}: {error_msg}\n"

            if len(error_results) > 5:
                result_msg += f"... 还有 {len(error_results) - 5} 个失败的模板"

        msg_type = "success" if error_count == 0 else "warning"
        self.show_message("批量导入结果", result_msg, msg_type)



    def delete_selected_templates(self):
        """删除选中的模板"""
        if not self.selected_templates:
            self.show_message("提示", "请先选择要删除的模板", "warning")
            return

        # 确认删除
        try:
            import tkinter as tk
            from tkinter import messagebox

            temp_root = tk.Tk()
            temp_root.withdraw()
            temp_root.lift()
            temp_root.attributes('-topmost', True)

            # 显示要删除的模板列表
            template_names = [t.get('name', '未知模板') for t in self.selected_templates]
            confirm_msg = f"确定要删除选中的 {len(self.selected_templates)} 个模板吗？\n\n"
            confirm_msg += "模板列表:\n"
            for i, name in enumerate(template_names[:5], 1):
                confirm_msg += f"{i}. {name}\n"
            if len(template_names) > 5:
                confirm_msg += f"... 还有 {len(template_names) - 5} 个模板\n"
            confirm_msg += "\n此操作不可撤销！"

            result = messagebox.askyesno("确认批量删除", confirm_msg, parent=temp_root)
            temp_root.destroy()

            if result:
                try:
                    success_count = 0
                    error_count = 0
                    error_messages = []

                    # 逐个删除模板
                    for template in self.selected_templates:
                        try:
                            if self.template_repo:
                                # 从数据库删除
                                db_id = template.get('id')  # 数据库主键ID
                                template_id = template.get('template_id')  # 模板业务ID

                                if db_id:
                                    # 优先使用数据库主键ID删除
                                    success = self.template_repo.delete(db_id)
                                    if success:
                                        success_count += 1
                                    else:
                                        error_count += 1
                                        error_messages.append(f"{template.get('name', '未知模板')}: 删除失败")
                                elif template_id:
                                    # 使用模板业务ID删除
                                    success = self.template_repo.delete_by_template_id(template_id)
                                    if success:
                                        success_count += 1
                                    else:
                                        error_count += 1
                                        error_messages.append(f"{template.get('name', '未知模板')}: 删除失败")
                                else:
                                    error_count += 1
                                    error_messages.append(f"{template.get('name', '未知模板')}: 无效的模板ID")
                            else:
                                # 模拟删除
                                success_count += 1
                        except Exception as e:
                            error_count += 1
                            error_messages.append(f"{template.get('name', '未知模板')}: {str(e)}")

                    # 清空选择
                    self.selected_templates.clear()

                    # 显示结果
                    if error_count == 0:
                        self.show_message("批量删除成功", f"成功删除 {success_count} 个模板！", "success")
                    else:
                        result_msg = f"批量删除完成！\n\n成功: {success_count} 个\n失败: {error_count} 个"
                        if error_messages:
                            result_msg += f"\n\n失败详情:\n" + "\n".join(error_messages[:5])
                            if len(error_messages) > 5:
                                result_msg += f"\n... 还有 {len(error_messages) - 5} 个错误"
                        self.show_message("批量删除结果", result_msg, "warning")

                    self.refresh_templates()

                except Exception as e:
                    self.show_message("删除失败", f"批量删除过程中发生错误: {str(e)}", "error")

        except Exception as e:
            self.show_message("错误", f"无法显示确认对话框: {str(e)}", "error")



    def refresh_templates(self):
        """刷新模板列表"""
        self.selected_templates.clear()
        self.load_templates()

    def view_template(self, template: Dict[str, Any]):
        """查看模板详情"""
        # 构建详情信息
        details = f"""模板详情:

名称: {template.get('name', '未知')}
类型: {template.get('type', '未知')}
时长: {template.get('duration', 0):.1f} 秒
画布比例: {template.get('canvas_ratio', '未知')}
片段数: {template.get('video_segment_count', 0)}
状态: {template.get('status', '未知')}
文件路径: {template.get('file_path', '未知')}
"""

        self.show_message("模板详情", details, "info")

    def delete_template(self, template: Dict[str, Any]):
        """删除单个模板"""
        try:
            import tkinter as tk
            from tkinter import messagebox

            temp_root = tk.Tk()
            temp_root.withdraw()
            temp_root.lift()
            temp_root.attributes('-topmost', True)

            # 确认删除
            result = messagebox.askyesno(
                "确认删除",
                f"确定要删除模板 '{template.get('name')}' 吗？\n此操作不可撤销！",
                parent=temp_root
            )

            temp_root.destroy()

            if result:
                try:
                    # 调用实际的删除逻辑
                    if self.template_repo:
                        # 从数据库删除
                        db_id = template.get('id')  # 数据库主键ID
                        template_id = template.get('template_id')  # 模板业务ID

                        if db_id:
                            # 优先使用数据库主键ID删除
                            success = self.template_repo.delete(db_id)
                            if success:
                                self.show_message("删除成功", f"模板 '{template.get('name')}' 删除成功！", "success")
                                self.refresh_templates()
                            else:
                                self.show_message("删除失败", f"无法删除模板 '{template.get('name')}'", "error")
                        elif template_id:
                            # 使用模板业务ID删除
                            success = self.template_repo.delete_by_template_id(template_id)
                            if success:
                                self.show_message("删除成功", f"模板 '{template.get('name')}' 删除成功！", "success")
                                self.refresh_templates()
                            else:
                                self.show_message("删除失败", f"无法删除模板 '{template.get('name')}'", "error")
                        else:
                            self.show_message("删除失败", "模板ID无效", "error")
                    else:
                        # 如果没有数据库连接，只是模拟删除
                        self.show_message("删除成功", f"模板 '{template.get('name')}' 删除成功！（模拟）", "success")
                        self.refresh_templates()

                except Exception as e:
                    self.show_message("删除失败", f"删除模板失败: {str(e)}", "error")

        except Exception as e:
            self.show_message("错误", f"无法显示确认对话框: {str(e)}", "error")
